package com.sa.oauth.controller;


import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.oauth2.config.SaOAuth2ServerConfig;
import cn.dev33.satoken.oauth2.processor.SaOAuth2ServerProcessor;
import cn.dev33.satoken.oauth2.strategy.SaOAuth2Strategy;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.sa.oauth.entity.SysPerson;
import com.sa.oauth.service.OAuthClientService;
import com.sa.oauth.service.Oauth2UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
public class OAuth2ServerController {
    @Resource
    private OAuthClientService oauthClientService;

    @Resource
    private Oauth2UserService oauth2userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/oauth2/*")
    public Object request() {
        System.out.println("------- 进入请求: " + SaHolder.getRequest().getUrl());
        return SaOAuth2ServerProcessor.instance.dister();
    }

    @RequestMapping("/oauth2/getuserid")
    public Object request(String openid) {
        System.out.println("------- 进入/oauth2/getuserid 请求: " + openid);
        SysPerson sysPerson = oauth2userService.getByOpenid(openid);
        return sysPerson;
    }


    @Autowired
    public void configOAuth2Server(SaOAuth2ServerConfig oauth2Server) {
//        List<Object> list = stringRedisTemplate.opsForHash().values(RedisKeys.CLINETS);
//
//        list.forEach(item -> oauth2Server.addClient(JSON.parseObject((String) item, SaClientModel.class)));

        //配置：未登录时返回的view
        // 未登录的视图
        SaOAuth2Strategy.instance.notLoginView = () -> {
            return new ModelAndView("login.html");
        };
        // 登录处理函数
        SaOAuth2Strategy.instance.doLoginHandle = (name, pwd) -> {
            // 使用Oauth2UserService进行数据库验证
            if (oauth2userService.verifyPassword(name,pwd)) {
                // 根据账号获取用户信息
                SysPerson sysPerson = oauth2userService.getByAccount(name);
                // 使用用户ID登录
                StpUtil.login(sysPerson.getId());
                return SaResult.ok().set("satoken", StpUtil.getTokenValue());
            }
            return SaResult.error("账号名或密码错误");
        };

        // 授权确认视图
        SaOAuth2Strategy.instance.confirmView = (clientId, scopes) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("clientId", clientId);
            map.put("scope", scopes);
            return new ModelAndView("confirm.html", map);
        };

    }


}
